import fre from "fs-extra";
import { CronJob } from "cron";
/**
    schedule 定时规则 https://www.npmjs.com/package/node-schedule
    *    *    *    *    *    *
    ┬    ┬    ┬    ┬    ┬    ┬
    │    │    │    │    │    │
    │    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
    │    │    │    │    └───── month (1 - 12)
    │    │    │    └────────── day of month (1 - 31)
    │    │    └─────────────── hour (0 - 23)
    │    └──────────────────── minute (0 - 59)
    └───────────────────────── second (0 - 59, OPTIONAL)
 */
import config from "../config/index";
import splitLogFile from "./split-log-file";
import analysisLogsAndWriteDB from "./analysis-logs";
import rmLogs from "./rm-logs";

const accessLogPath = config.accessLogPath;

const accessLogPathFiles = fre.readdirSync(accessLogPath);
console.log(`accessLogPath:`, accessLogPath, fre.pathExistsSync(accessLogPath));

/**
 * 开始定时任务
 * @param cronTime corn规则
 * @param onTick 回调函数
 * @returns void
 */
export const schedule = (cronTime: string, onTick: () => void) => {
  if (!cronTime || typeof onTick !== "function") return;

  const c = new CronJob(cronTime, onTick, null, true, "Asia/Shanghai");

  process.on("exit", () => c.stop());
};

/**
 * 定时拆分日志文件
 */
export const splitLogFileTimed = () => {
  const cronTime = "0 0 0 * * *";
  schedule(cronTime, () => splitLogFile(accessLogPath));
};

/**
 * 定时分析日志文件
 */
export const analysisLogsTimed = () => {
  // analysisLogsAndWriteDB(accessLogPath);
  const cronTime = "0 0 4 * * *";
  schedule(cronTime, () => analysisLogsAndWriteDB(accessLogPath));
};

/**
 * 定时删除过期的日志文件
 */
export const rmLogsTimed = () => {
  const cronTime = "0 30 4 * * *";
  schedule(cronTime, () => rmLogs(accessLogPath));
};
